# 日志中间件

from fastapi import Request
from loguru import logger
import time
from http import HTTPStatus

async def log_middleware(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = (time.time() - start_time) * 1000
    
     # 获取 HTTP 状态码对应的状态描述
    status_reason = HTTPStatus(response.status_code).phrase if response.status_code in HTTPStatus.__members__.values() else "Unknown"

    log_data = {
        "path": request.url.path,
        "method": request.method,
        "status": response.status_code,
        "duration": f"{process_time:.2f}ms",
        "client": request.client.host if request.client else "unknown"
    }
    
    if response.status_code == 200:
        logger.bind(**log_data).info(f"{request.method} {request.url.path} | {response.status_code} {status_reason}")
    else:
        logger.bind(**log_data).error(f"{request.method} {request.url.path} | {response.status_code} {status_reason}")
    return response